/* 
 Example 6.1
 Read the outputs from a Sharp GP2Y0A21YK0F Analog Distance Sensor
 tronixstuff.com/tutorials > Chapter Six
 */

#include <LiquidCrystal.h>
// we need this library for the LCD commands
LiquidCrystal lcd(10,11,12,13,14,15,16);
/* tells Arduino which pins the LCD is connected to;
 in this case 10~16, which match the pinouts on chassis
 BUS2 socket
 */


float sensor = 0;
int cm = 0;
float inch = 0;
void setup()
{
  lcd.begin(16, 2); // tells Arduino the LCD dimensions
  lcd.setCursor(0,0);
  lcd.print("* tronixstuff *");
  // print text and move cursor to start of next line
  lcd.setCursor(0,1);
  lcd.print("  example 6.1");
  delay(4000);
  lcd.clear(); // clear LCD screen
  lcd.setCursor(0,0);
}


void loop()
{
  sensor = analogRead(5);
  if (sensor<=90)
  {
    lcd.setCursor(0,0);
    lcd.print("  * infinite *");
    lcd.setCursor(0,1);
    lcd.print("  * distance *");
  } else if (sensor<100) // 80cm
  {
    cm = 80;
    inch = 31;
  } else if (sensor<110) // 70 cm
  {
    cm = 70;
    inch = 28;
  } else if (sensor<118) // 60cm
  {
    cm = 60;
    inch = 24;
  } else if (sensor<147) // 50cm
  {
    cm = 50;
    inch = 20;
  } else if (sensor<188) // 40 cm
  {
    cm = 40;
    inch = 16;
  } else if (sensor<230) // 30cm
  {
    cm = 30;
    inch = 12;
  } else if (sensor<302) // 25 cm
  {
    cm = 25;
    inch = 10;
  } else if (sensor<360) // 20cm
  {
    cm = 20;
    inch = 8;
  } else if (sensor<505) // 15cm
  {
    cm = 15;
    inch = 6;
  } else if (sensor<510) // 10 cm
  {
    cm = 10;
    inch = 4;
  } else if (sensor>=510) // too close!
  {
    lcd.setCursor(0,0);
    lcd.print("   * Whoa! *");
    lcd.setCursor(0,1);
    lcd.print(" * Too close *");
  } 
  // display reading  
  lcd.setCursor(0,0);
  lcd.print("                 ");
  lcd.setCursor(0,1);
  lcd.print("                 ");
  lcd.setCursor(0,0);
  lcd.print(" Metric: ");
  lcd.print(cm);
  lcd.print(" cm");
  lcd.setCursor(0,1);
  lcd.print(" Imperial: ");
  lcd.print(inch,0);
  lcd.print(" in");
  delay(250); // slow things down a bit, to smooth out the display jitters
}


